<template>
  <div class="form-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>新用户注册</span>
        </div>
      </template>
      <el-form
        :model="regForm"
        :rules="rules"
        ref="formRef"
        label-width="0px"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="regForm.username"
            placeholder="请输入用户名"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="regForm.password"
            placeholder="请输入密码"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            type="password"
            v-model="regForm.confirmPassword"
            placeholder="请再次输入密码"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="regForm.email"
            placeholder="请输入电子邮箱 (可选)"
            size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            style="width: 100%;"
            size="large"
            :loading="loading"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
      <div class="footer-link">
        已有账号？ <router-link to="/login">立即登录</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { registerApi } from '@/api/auth';
import type { RegisterRequest } from '@/types/api';

const router = useRouter();
const formRef = ref<FormInstance>();
const loading = ref(false);

const regForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: ''
});

//表单验证
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== regForm.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

const rules: FormRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur', required: true }],
  email: [{ type: 'email', message: '请输入有效的电子邮箱地址', trigger: ['blur', 'change'] }]
};

// 【核心修正】重写 handleRegister 函数的验证逻辑
const handleRegister = async () => {
  if (!formRef.value) return;

  try {
    // 第一步：直接 await 表单验证。如果验证失败，它会抛出异常并被 catch 捕获。
    await formRef.value.validate();

    // 如果代码能执行到这里，说明验证成功
    loading.value = true;

    const apiData: RegisterRequest = {
      username: regForm.username,
      password: regForm.password,
      email: regForm.email
    };

    const responseMessage = await registerApi(apiData);

    ElMessage.success(responseMessage || '注册成功！现在您可以登录了。');
    router.push({ name: 'Login' });

  } catch (error) {
    // 捕获验证失败的错误或API请求的错误
    if (error instanceof Error) {
        // 这是API请求错误，已在拦截器中提示
        console.error("注册失败:", error);
    } else {
        // 这是表单验证失败的错误
        console.log('表单验证失败:', error);
        ElMessage.error('请检查表单输入是否正确。');
    }
  } finally {
    // 无论成功或失败，最后都结束加载状态
    loading.value = false;
  }
};
</script>

<style scoped>
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}
.form-card {
  width: 400px;
}
.footer-link {
  margin-top: 10px;
  text-align: center;
  font-size: 14px;
}
</style>
